#pragma once

#include <iostream>
#include <time.h>
#include <stdarg.h>

#define Info    0
#define Debug   1
#define Warning 2
#define Error   3
#define Fatal   4

#define SIZE 1024

#define SCREEN     5
#define ONE_FILE   6
#define CLASS_FILE 7

#define LogFile "log.txt"

class Log
{
public:

    void Enable(int method)
    {
        _method = method;
    }

    std::string LevelToString(int level)
    {
        switch(level)
        {
            case Info : return "Info";
            case Debug : return "Debug";
            case Warning : return "Warning";
            case Error : return "Error";
            case Fatal : return "Fatal";
        }
    }

    void PrintOneFile(const std::string& logname, const std::string& logtxt)
    {
        std::string filename = _path + logname;
        int fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666);
        if(fd < 0)
            return;

        write(fd, logtxt.c_str(), logtxt.size());
        close(fd);
    }


    void PrintClassFile(int level, const std::string& logtxt)
    {
        std::string filename = LogFile;
        filename += ".";
        filename += LevelToString(level); 
        PrintOneFile(filename, logtxt);
    }

    void PrintLog(int level, const std::string& logtxt)
    {
        //std :: cout << _method << std::endl;
        switch(_method)
        {
            case SCREEN: 
               // std::cout << "111" << std::endl;
                std::cout << logtxt << std::endl;
                break;
            case ONE_FILE:
              //  std::cout << "2222" << std::endl;
                PrintOneFile(LogFile, logtxt);
                break;
            case CLASS_FILE:
                PrintClassFile(level, logtxt);
                break;
        }
    }

    void logmessage(int level, const char* format, ...)
    {
        time_t t = time(nullptr);
        struct tm* _time = localtime(&t);
        char leftbuffer[SIZE];
        snprintf(leftbuffer, sizeof(leftbuffer),"[%s][%d-%d-%d %d:%02d:%02d]", LevelToString(level).c_str(),
                _time->tm_year + 1900, _time->tm_mon + 1,_time->tm_mday,
                _time->tm_hour, _time->tm_min, _time->tm_sec);
        
        va_list s;
        va_start(s, format);
        char rigthbuffer[SIZE];
        vsnprintf(rigthbuffer, sizeof(rigthbuffer), format, s);
        va_end(s);

        char logtxt[SIZE * 2];
        snprintf(logtxt, sizeof(logtxt), "%s %s\n",leftbuffer, rigthbuffer);

        // std::cout << logtxt << std::endl;
        // printf("[%d-%d-%d %d:%02d:%02d]\n", _time->tm_year + 1900, _time->tm_mon + 1,
        //          _time->tm_mday, _time->tm_hour, _time->tm_min, _time->tm_sec);

        PrintLog(level, logtxt);
    }

private:
    //默认打显示屏
    int _method = SCREEN;
    std::string _path = "./log/";  // 要自己先创建目录

};